#! /usr/bin/env node

import { packGame } from "../publish/PublishFactory";

import fs = require('fs');
import path = require("path");
import inquirer = require("inquirer");
import chalk = require("chalk");

const programPath = process.cwd();
const projectCfgFileName = "project.cfg";
const templatePath = path.join(__dirname, '../../assets/config/');

function logFunc(msg) {
    console.log(msg);
}

function askTemplate(list: string[]) {
    let questions = [
        {
            type: "list",
            name: "name",
            message: "请选择发布模板?",
            choices: list,
            default: 0,
            pageSize: 20,
            loop: false
        }
    ];
    return inquirer.prompt(questions);
};

function askVersion(v?: string) {
    let msg = v ? "请输入版本号(最近版本 " + v + "):" : "请输入版本号:";
    let questions = [
        {
            type: "input",
            name: "version",
            message: msg,
            default: v || '1.0.0'
        },
    ];
    return inquirer.prompt(questions);
};

function askCheckRes() {
    let questions = [
        {
            type: 'confirm',
            name: 'checkRes',
            message: '是否检测资源?'
        }
    ];
    return inquirer.prompt(questions);
};

function askContinue() {
    let questions = [
        {
            type: 'confirm',
            name: 'continue',
            message: '请确认是否开始打包游戏'
        }
    ];
    return inquirer.prompt(questions);
};

function logHelp() {
    console.log('\n');
    console.log("Usage: pack [options]\n");
    console.log("Options:");
    console.log("   -c, --config            从配置文件中选择模板，发布版本");
    console.log("   -c, --config default    从配置文件中选择默认模板，发布版本");
    console.log("   -t, --template          从自定义文件中选择模板，发布版本");
    console.log('\n');
}

async function run(argv) {

    if (argv[0]) {
        let argv1 = argv[0].toLowerCase();
        if (argv1 === '-c' || argv1 === '--config') {

            let cfgFilePath = path.join(programPath, projectCfgFileName);
            if (!fs.existsSync(cfgFilePath)) {
                console.log("项目配置文件不存在");
                return;
            }

            let str = fs.readFileSync(cfgFilePath);
            let projectVo = JSON.parse(str.toString());

            let publishArray = projectVo['publishs'];
            let publishObj = {};
            let templateList = [];
            for (let i = 0; i < publishArray.length; i++) {
                let name = publishArray[i]['name'];
                publishObj[name] = publishArray[i];
                templateList.push(name);
            }

            if (templateList.length == 0) {
                console.log("未找到项目发布模板");
                return;
            }

            let name = templateList[0];
            let publishVo = publishObj[name];
            let version = publishVo['preVersion'];
            let checkRes = true;

            if (argv[1]) {
                let argv2 = argv[1].toLowerCase();
                if (argv2 === 'default') {
                    console.log("发布模板: " + chalk.blue(name));
                    console.log(publishObj[name]);
                    console.log("版本号: " + chalk.blue(version));
                    console.log("检测资源: " + chalk.blue("YES"));
                }
                else {
                    logHelp();
                    return;
                }
            }
            else {
                let templateObj = await askTemplate(templateList);
                name = templateObj['name'];
                publishVo = publishObj[name];
                console.log(publishObj[name]);
                let versionObj = await askVersion(publishVo['preVersion']);
                version = versionObj['version'];
                let checkResObj = await askCheckRes();
                checkRes = checkResObj['checkRes'];
            }

            let res = await askContinue();
            if (!res['continue']) {
                console.log(chalk.white.bgRedBright.bold("退出发布！"))
                return;
            }

            console.log(chalk.yellow("======================================================="));

            packGame(publishVo, projectVo, version, checkRes, logFunc, function (success: boolean) {
                console.log(chalk.yellow("======================================================="));
                if (success) {
                    if (publishVo['preVersion'] != version) {
                        publishVo['preVersion'] = version;
                        let publishs = [publishVo];
                        for (let i in publishObj) {
                            if (i != name) {
                                publishs.push(publishObj[i]);
                            }
                        }
                        projectVo['publishs'] = publishs;
                        fs.writeFileSync(cfgFilePath, JSON.stringify(projectVo));
                    }
                    console.log(chalk.white.bgGreenBright.bold("发布成功！"))
                } else {
                    console.log(chalk.white.bgRedBright.bold("发布失败！"))

                }
            })

        }
        else if (argv1 === '-t' || argv1 === '--template') {
            let dirArray = fs.readdirSync(templatePath);
            let nameList = [];
            for (let i = 0; i < dirArray.length; i++) {
                nameList.push(dirArray[i].split('.')[0]);
            }

            if (nameList.length <= 0) {
                console.log("暂无模板");
                return;
            }

            let questions = [
                {
                    type: "rawlist",
                    name: "fileName",
                    message: "请选择配置模板?",
                    choices: nameList,
                    default: 0,
                    pageSize: 100,
                    loop: false
                }
            ];
            let fileName = await inquirer.prompt(questions);

            let filePath = path.join(templatePath, fileName['fileName'] + '.cfg');
            let str = fs.readFileSync(filePath);
            let projectVo = JSON.parse(str.toString());
            let publishVo = projectVo['publish'];
            console.log(publishVo);
            let version = publishVo['preVersion'] || '1.0.0';
            let checkRes = true;

            let versionObj = await askVersion(version);
            version = versionObj['version'];
            let checkResObj = await askCheckRes();
            checkRes = checkResObj['checkRes'];

            let res = await askContinue();
            if (!res['continue']) {
                console.log(chalk.white.bgRedBright.bold("退出发布！"))
                return;
            }

            console.log(chalk.yellow("======================================================="));

            packGame(publishVo, projectVo, version, checkRes, logFunc, function (success: boolean) {
                console.log(chalk.yellow("======================================================="));
                if (success) {
                    if (publishVo['preVersion'] != version) {
                        publishVo['preVersion'] = version;
                        projectVo['publish'] = publishVo;
                        fs.writeFileSync(filePath, JSON.stringify(projectVo));
                    }
                    console.log(chalk.white.bgGreenBright.bold("发布成功！"))
                } else {
                    console.log(chalk.white.bgRedBright.bold("发布失败！"))

                }
            })
        }
        else {
            logHelp();
        }
    }
    else {
        logHelp();
    }
}

run(process.argv.slice(2));